import { defineStore } from 'pinia'

export const useGameStore = defineStore('game', {
  state: () => ({
    games: {
      size: 0,
      board: [],
      // 分数
      score: 0,
      comboCount: 0,
      isProcessing: false,
      effectChainDepth: 0,
      // 步数
      steps: 0,
      // 新增初始化状态,用来解决Game.vue当中重新开始游戏时，步数异常的问题
      isInitializing: false,
      // 需要消除的冰冻卡片
      frozenCards: 0,
    },
    MAX_CHAIN_DEPTH: 10,
    MAX_COMBO_COUNT: 30
  }),

  actions: {
    dropCards() {
      const size = this.games.size;
      for (let col = 0; col < size; col++) {
        let emptySlots = 0;
        
        for (let row = size - 1; row >= 0; row--) {
          if (!this.games.board[row][col]) {
            emptySlots++;
          } else if (emptySlots > 0) {
            this.games.board[row + emptySlots][col] = {...this.games.board[row][col]};
            this.games.board[row + emptySlots][col].row = row + emptySlots;
            this.games.board[row][col] = null;
          }
        }
      }
    },

    refillBoard() {
      const suits = ['spade', 'heart', 'diamond', 'club'];
      for (let col = 0; col < this.games.size; col++) {
        for (let row = 0; row < this.games.size; row++) {
          if (!this.games.board[row][col]) {
            const newCard = {
              suit: suits[Math.floor(Math.random() * suits.length)],
              row,
              col,
              isMatched: false,
              isChanging: false,
              isHighlighted: false,
              specialType: 'none'
            };
            this.games.board[row][col] = newCard;
          }
        }
      }
    },

    removeCards(matchedPositions, removeSpecialCards = false) {
      if (matchedPositions.size === 0) return [];
      
      const positionsArray = Array.from(matchedPositions);
      const specialCardsToTrigger = [];
      
      positionsArray.forEach((pos) => {
        const [row, col] = pos.split(',').map(Number);
        const card = this.games.board[row][col];
        
        if (!card) return;
        
        // 关键修改：无论 removeSpecialCards 是什么值，都要收集特殊卡片
        if (card.specialType !== 'none') {
          specialCardsToTrigger.push({
            row,
            col,
            type: card.specialType,
            suit: card.suit
          });
        }
        
        // 总是移除匹配的卡片
        this.games.score += 10 + this.games.comboCount * 5;
        this.games.board[row][col] = null;
      });
      
      return specialCardsToTrigger;
    },

    toggleCardSuit(row, col) {
      const card = this.games.board[row][col];
      if (card) {
        const order = ['spade', 'heart', 'diamond', 'club'];
        const index = (order.indexOf(card.suit) + 1) % 4;
        this.games.board[row][col] = {
          ...card,
          suit: order[index],
          isChanging: true
        };
        
        setTimeout(() => {
          if (this.games.board[row][col]) {
            this.games.board[row][col].isChanging = false;
          }
        }, 300);
      }
    },

    findAdjacentSpecialCards(row, col) {
      const adjacentCards = [];
      const directions = [[-1, 0], [1, 0], [0, -1], [0, 1]];
      
      for (const [dr, dc] of directions) {
        const newRow = row + dr;
        const newCol = col + dc;
        
        if (newRow >= 0 && newRow < this.games.size && newCol >= 0 && newCol < this.games.size) {
          const card = this.games.board[newRow][newCol];
          if (card && card.specialType !== 'none') {
            adjacentCards.push({
              row: newRow,
              col: newCol,
              type: card.specialType,
              suit: card.suit
            });
          }
        }
      }
      
      return adjacentCards;
    },

    getEffectRange(effect) {
      const matchedPositions = new Set();
      switch(effect.type) {
        case 'horizontal':
          for (let c = 0; c < this.games.size; c++) {
            matchedPositions.add(`${effect.row},${c}`);
          }
          break;
        case 'vertical':
          for (let r = 0; r < this.games.size; r++) {
            matchedPositions.add(`${r},${effect.col}`);
          }
          break;
        case 'joker':
          for (let r = 0; r < this.games.size; r++) {
            for (let c = 0; c < this.games.size; c++) {
              if (this.games.board[r][c] && this.games.board[r][c].suit === effect.suit) {
                matchedPositions.add(`${r},${c}`);
              }
            }
          }
          break;
        case 'bomb':
          for (let r = Math.max(0, effect.row - 1); r <= Math.min(this.games.size - 1, effect.row + 1); r++) {
            for (let c = Math.max(0, effect.col - 1); c <= Math.min(this.games.size - 1, effect.col + 1); c++) {
              matchedPositions.add(`${r},${c}`);
            }
          }
          break;
      }
      return matchedPositions;
    },

    createSpecialCards(specialCardsInfo) {
      specialCardsInfo.forEach(info => {
        const {row, col, type, suit} = info;
        if (row >= 0 && row < this.games.size && col >= 0 && col < this.games.size) {
          // 如果位置为空，创建一个新卡片
          if (!this.games.board[row][col]) {
            this.games.board[row][col] = {
              suit: suit || 'spade',
              row,
              col,
              isMatched: false,
              isChanging: false,
              isHighlighted: false,
              specialType: type
            };
          } else {
            // 如果位置已有卡片，只更新特殊类型
            this.games.board[row][col] = { 
              ...this.games.board[row][col],
              specialType: type
            };
          }
        }
      });
    },

    incrementEffectChainDepth() {
      this.games.effectChainDepth++;
    },

    resetEffectChainDepth() {
      this.games.effectChainDepth = 0;
    },

    checkMatches() {
      const matchedPositions = new Set();
      const specialCardsToCreate = [];
      let hasMatches = false;

      // 水平检测
      for (let row = 0; row < this.games.size; row++) {
        for (let col = 0; col < this.games.size - 2;) {
          if (!this.games.board[row][col]) {
            col++;
            continue;
          }

          const suit = this.games.board[row][col].suit;
          let matchLength = 1;

          while (col + matchLength < this.games.size &&
          this.games.board[row][col + matchLength]?.suit === suit) {
            matchLength++;
          }

          if (matchLength >= 3) {
            hasMatches = true;
            for (let i = 0; i < matchLength; i++) {
              const c = col + i;
              matchedPositions.add(`${row},${c}`);
            }

            // 生成特殊卡片
            if (matchLength === 4) {
              specialCardsToCreate.push({
                row,
                col: col + Math.floor(matchLength / 2),
                type: 'horizontal',
                suit
              });
            } else if (matchLength >= 5) {
              specialCardsToCreate.push({
                row,
                col: col + Math.floor(matchLength / 2),
                type: 'joker',
                suit
              });
            }
            col += matchLength;
          } else {
            col++;
          }
        }
      }

      // 垂直匹配检测
      for (let col = 0; col < this.games.size; col++) {
        for (let row = 0; row < this.games.size - 2;) {
          if (!this.games.board[row][col]) {
            row++;
            continue;
          }

          const suit = this.games.board[row][col].suit;
          let matchLength = 1;

          while (row + matchLength < this.games.size &&
          this.games.board[row + matchLength][col]?.suit === suit) {
            matchLength++;
          }

          if (matchLength >= 3) {
            hasMatches = true;
            for (let i = 0; i < matchLength; i++) {
              const r = row + i;
              matchedPositions.add(`${r},${col}`);
            }

            // 生成特殊卡片
            if (matchLength === 4) {
              specialCardsToCreate.push({
                row: row + Math.floor(matchLength / 2),
                col,
                type: 'vertical',
                suit
              });
            } else if (matchLength >= 5) {
              specialCardsToCreate.push({
                row: row + Math.floor(matchLength / 2),
                col,
                type: 'joker',
                suit
              });
            }
            row += matchLength;
          } else {
            row++;
          }
        }
      }

      // 检查T型和L型匹配
      this.checkTAndLMatches(matchedPositions, specialCardsToCreate);

      // 关键修改：从匹配集合中移除特殊卡片的位置，以免被消除
      specialCardsToCreate.forEach(card => {
        const pos = `${card.row},${card.col}`;
        matchedPositions.delete(pos);
      });

      return { hasMatches, matchedPositions, specialCardsToCreate };
    },

    checkTAndLMatches(matchedPositions, specialCardsToCreate) {
      const tPatterns = [
        { pattern: [[0, -1], [0, 0], [0, 1], [-1, 0], [1, 0]], name: "T-up" },
        { pattern: [[0, -1], [0, 0], [0, 1], [1, 0], [2, 0]], name: "T-down" },
        { pattern: [[-1, 0], [0, 0], [1, 0], [0, -1], [0, 1]], name: "T-left" },
        { pattern: [[-1, 0], [0, 0], [1, 0], [0, 1], [0, 2]], name: "T-right" }
      ];

      const lPatterns = [
        { pattern: [[0, 0], [1, 0], [2, 0], [0, 1], [0, 2]], name: "L-top-left" },
        { pattern: [[0, 0], [1, 0], [2, 0], [2, 1], [2, 2]], name: "L-top-right" },
        { pattern: [[0, 0], [0, 1], [0, 2], [1, 2], [2, 2]], name: "L-bottom-right" },
        { pattern: [[0, 0], [0, 1], [0, 2], [1, 0], [2, 0]], name: "L-bottom-left" }
      ];

      for (let row = 0; row < this.games.size; row++) {
        for (let col = 0; col < this.games.size; col++) {
          if (!this.games.board[row][col]) continue;

          const suit = this.games.board[row][col].suit;

          // 检查T型模式
          for (const {pattern, name} of tPatterns) {
            let isValid = true;
            const positions = [];

            for (const [dr, dc] of pattern) {
              const r = row + dr;
              const c = col + dc;

              if (r < 0 || r >= this.games.size || c < 0 || c >= this.games.size ||
                  !this.games.board[r][c] || this.games.board[r][c].suit !== suit) {
                isValid = false;
                break;
              }

              positions.push([r, c]);
            }

            if (isValid) {
              positions.forEach(([r, c]) => {
                matchedPositions.add(`${r},${c}`);
              });

              // 在中心位置生成炸弹特效卡片
              specialCardsToCreate.push({
                row,
                col,
                type: 'bomb',
                suit
              });
            }
          }

          // 检查L型模式
          for (const {pattern, name} of lPatterns) {
            let isValid = true;
            const positions = [];

            for (const [dr, dc] of pattern) {
              const r = row + dr;
              const c = col + dc;

              if (r < 0 || r >= this.games.size || c < 0 || c >= this.games.size ||
                  !this.games.board[r][c] || this.games.board[r][c].suit !== suit) {
                isValid = false;
                break;
              }

              positions.push([r, c]);
            }

            if (isValid) {
              positions.forEach(([r, c]) => {
                matchedPositions.add(`${r},${c}`);
              });

              // 在中心位置生成炸弹特效卡片
              specialCardsToCreate.push({
                row,
                col,
                type: 'bomb',
                suit
              });
            }
          }
        }
      }
    },

      // 生成冰冻卡片
  generateFrozenCards(count) {
    const positions = [];
    const size = this.games.size;
    
    while (positions.length < count) {
      const row = Math.floor(Math.random() * size);
      const col = Math.floor(Math.random() * size);
      
      // 确保位置不重复，且该位置没有其他特殊卡片
      if (!positions.some(pos => pos.row === row && pos.col === col) && 
          this.games.board[row][col].specialType === 'none') {
        positions.push({ row, col });
      }
    }
    
    // 在棋盘上设置冰冻卡片
    positions.forEach(pos => {
      this.games.board[pos.row][pos.col].specialType = 'freeze';
      this.games.board[pos.row][pos.col].isFrozen = true;
    });
    
    this.games.frozenCards = count;
  },

  // 检查并更新冰冻卡片数量
  updateFrozenCardsCount() {
    let count = 0;
    for (let row = 0; row < this.games.size; row++) {
      for (let col = 0; col < this.games.size; col++) {
        if (this.games.board[row][col] && this.games.board[row][col].specialType === 'freeze') {
          count++;
        }
      }
    }
    this.games.frozenCards = count;
  },

  // 重写removeCards函数（通过新增函数的方式）
  removeCardsWithFrozenCheck(matchedPositions) {
    if (matchedPositions.size === 0) return [];
    
    const positionsArray = Array.from(matchedPositions);
    const specialCardsToTrigger = [];
    let frozenCardsRemoved = 0;
    
    positionsArray.forEach((pos) => {
      const [row, col] = pos.split(',').map(Number);
      const card = this.games.board[row][col];
      
      if (!card) return;
      
      // 记录被移除的冰冻卡片
      if (card.specialType === 'freeze') {
        frozenCardsRemoved++;
      }
      
      if (card.specialType !== 'none') {
        specialCardsToTrigger.push({
          row,
          col,
          type: card.specialType,
          suit: card.suit
        });
      }
      
      this.games.score += 10 + this.games.comboCount * 5;
      this.games.board[row][col] = null;
    });
    
    // 更新冰冻卡片计数
    if (frozenCardsRemoved > 0) {
      this.games.frozenCards = Math.max(0, this.games.frozenCards - frozenCardsRemoved);
    }
    
    return specialCardsToTrigger;
  }
  }
})
